/**   
* @Title: WeatherDataCollectionServiceImpl.java 
* @Package com.yao.spring.cloud.weather.service.impl 
* @Description: TODO(用一句话描述该文件做什么) 
* @author yaoym
* @date 2018年3月26日 下午2:44:24 
* @version V1.0   
*/
package com.yao.spring.cloud.weather.service.impl;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.yao.spring.cloud.weather.service.WeatherDataCollectionService;

/**
 * @Description:
 * @author yaoym
 * @date 2018年3月26日 下午2:44:24
 * @version V1.0
 */
@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {

	private static final Logger logger = LoggerFactory.getLogger(WeatherDataCollectionServiceImpl.class);

	private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";

	private static final long TIME_OUT = 29 * 60L;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public void syncDataByCityID(String cityID) {
		String uri = WEATHER_URI + "citykey=" + cityID;
		this.saveWeatherData(uri);
	}

	/**
	 * 将天气数据保存到内存中
	 * 
	 * @Description:
	 * @since 2018年3月23日 上午9:35:45
	 * @author yaoym
	 * @param uri
	 */
	private void saveWeatherData(String uri) {
		logger.info("保存天气数据到redis。");

		final String key = uri;
		ResponseEntity<String> respStr = null;
		String strBody = null;

		ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
		// 调用天气接口获取天气数据
		respStr = restTemplate.getForEntity(uri, String.class);
		strBody = respStr.getBody();
		// 将获取到的天气数据保存到redis中
		ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
	}

}
